package mysql

import (
	"crypto/md5"
	"encoding/hex"
	"personnel-management/models"
	"personnel-management/pkg/snowflake"
	"time"
)

const secret = "wutianjiao.com"

//密码加密
func encryptPassword(data []byte) (result string) {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum(data))
}

//注册
func Register(user *models.User) (err error) {
	u := db.Where("user_name = ?", user.UserName).Find(user)

	if u.RowsAffected > 0 {
		// 用户已存在
		return ErrorUserExit
	}
	//生成user_id
	userID, err := snowflake.GetID()
	if err != nil {
		return ErrorGenIDFailed
	}
	// 生成加密密码
	password := encryptPassword([]byte(user.Password))
	// 把用户插入数据库
	db.Table("users").Create(map[string]interface{}{
		"user_id": userID, "password": password, "user_name": user.UserName, "phone_number": user.PhoneNumber, "email": user.Email, "created_at": time.Now(), "updated_at": time.Now(),
	})
	return
}

//登录
func Login(user *models.LoginUser) (err error) {
	originPassword := user.Password
	u := db.Table("users").Where("user_name = ?", user.UserName).Find(&user)
	if u.RowsAffected == 0 {
		// 用户不存在
		return ErrorUserNotExit
	}
	var use models.LoginUser
	db.Table("users").Select("password").Where("user_name = ?", user.UserName).Find(&use)
	password := encryptPassword([]byte(originPassword))
	if use.Password != password {
		return ErrorPasswordWrong
	}
	return
}

//得到用户列表
func GetUserList() (userList []*models.User, err error) {
	db.Table("users").Select("user_name", "phone_number", "email", "user_id").Find(&userList)
	return
}

//得到当前用户信息
func GetUserMessage(username string) (usermessage *models.User, err error) {
	db.Table("users").Select("user_name", "phone_number", "email", "user_id").Where("user_name = ?", username).First(&usermessage)
	return
}

//修改当前用户信息
func UpdateUserDetailByName(userid int64, userName string, user *models.User) (err error) {
	var User = models.User{}
	db.Table("users").Where("user_name = ?", user.UserName).Find(&User)
	if User.UserName != "" && User.UserName != userName {
		// 用户已经存在
		return ErrorUserExit
	}
	user.Password = encryptPassword([]byte(user.Password))

	db.Table("users").Where("user_id = ?", userid).Updates(map[string]interface{}{"phone_number": user.PhoneNumber, "user_name": user.UserName, "password": user.Password, "email": user.Email, "updated_at": time.Now()})
	return err
}

//删除用户
func DeleteUserDetailByID(userid int64) (err error) {
	db.Table("users").Where("user_id = ?", userid).Delete(userid)
	return err
}
